import createDraw from '@/utils/Draw'
import { Query } from '@/utils/Query'
import { message } from 'ant-design-vue'
import { ref } from 'vue'
export const QEvent = (map) => {
  const data = []
  const draw = ref()
  const visible = ref(false)
  const evisible = ref(false)
  const loading = ref(false)
  //拉框查询,获取框选范围坐标
  const queryBox = (map) => {
    //创建画布
    const source = new ol.source.Vector({
      wrapx: false,
    })
    const layer = new ol.layer.Vector({
      source: source,
    })
    map.value.addLayer(layer)
    //创建画笔,并绘制
    draw.value = createDraw({
      type: 'Box',
      source: source,
      callback: BoxSuccess,
    })
    map.value.addInteraction(draw.value)
    //回调,绘制完成之后,清除画笔
    function BoxSuccess(e) {
      //获取几何信息,geom.feature.values_.geometry
      const geom = e.feature.values_.geometry
      //查询范围内的所有事件
      const service = { docName: 'guanggu', layerId: 2 }
      Query.queryByGeom({
        geom: geom,
        service: service,
        callback: querySuccess,
      })
      //查询事件成功回调
      function querySuccess(result) {
        //判断,如果获取的事件数量为0,则报错
        if (result.TotalCount != 0) {
          //初始化Zondy.Format.PolygonJSON类
          var format = new Zondy.Format.PolygonJSON()
          //将MapGIS要素JSON反序列化为ol.Feature类型数组
          var features = format.read(result)
          //提取数据
          features.forEach((element) => {
            data.push(
              Object.assign({}, { FID: element.id_ }, element.values_.values_)
            )
          })
          //清除画笔
          map.value.removeInteraction(draw.value)
          console.log(data)
          //2s后显示弹框
          loading.value = true
          setTimeout(() => {
            loading.value = false
            visible.value = true
            source.clear()
          }, 2000)
        } else {
          source.clear()
          message.error('该范围内没有事件!')
        }
      }
    }
  }
  return {
    data,
    visible,
    evisible,
    loading,
    queryBox,
  }
}
